package service

import (
	"awesomeProject/app/model"
	"awesomeProject/app/request"
	"awesomeProject/app/response"
	"awesomeProject/global"
	"github.com/fatih/structs"
	"sort"
)

type ConfigSrv struct{}

var configSrv ConfigSrv

func (r *ConfigSrv) FindByName(name string) model.Config {
	var config model.Config
	_ = global.Gorm.Where("name = ?", name).First(&config).Error
	return config
}

func (r *ConfigSrv) UpdateValue(name string, value string) error {
	var config model.Config
	_ = global.Gorm.Where("name = ?", name).First(&config).Error
	updateData := map[string]interface{}{}
	updateData["value"] = value
	err := global.Gorm.Model(&config).Updates(updateData).Error
	return err
}

func (r *ConfigSrv) Update(req request.ConfigUpdate) response.Resp {
	updates := structs.Map(req)

	if err := global.Gorm.Model(&model.Config{}).Updates(updates).Error; err != nil {
		return response.ErrStore
	}

	return response.OK
}

func (r *ConfigSrv) UpdateAllLimit(allowIp string, banIp string, ipRemark string) response.Resp {
	if err := r.UpdateValue("allow_ip", allowIp); err != nil {
		return response.ErrUpdate.SetMsg("更新失败！")
	}
	if err := r.UpdateValue("ban_ip", banIp); err != nil {
		return response.ErrUpdate.SetMsg("更新失败！")
	}
	if err := r.UpdateValue("ip_remark", ipRemark); err != nil {
		return response.ErrUpdate.SetMsg("更新失败！")
	}
	return response.OK
}

func (r ConfigSrv) GetAllLimit() response.Resp {
	var configData map[string]interface{}
	configData = make(map[string]interface{})

	var configs []model.Config
	err := global.Gorm.Where("status = ?", 1).Find(&configs).Error
	if err != nil {
		return response.ErrUpdate.SetMsg("获取配置信息失败！")
	}
	var keys = [...]string{"allow_ip", "ban_ip", "ip_remark"}

	for _, config := range configs {
		index := sort.Search(len(keys), func(i int) bool {
			return keys[i] >= config.Name
		})
		if index < len(keys) && keys[index] == config.Name {
			configData[config.Name] = config.Value
		}
	}
	return response.OK.WithData(configData)
}
